package com.geaosu.filesselector;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.geaosu.filesselector.widget.BreadCrumbsView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class FilesManager extends AppCompatActivity {
    public static final int SELECT_FILE_RESULT_CODE = 8848;          // 返回码
    private static final int SELECT_MODE_SING = 1;                          // 单选模式
    private static final int SELECT_MODE_MULTIPLE = 2;                  // 多选模式
    private int SELECT_MODE_DEFAULT = SELECT_MODE_SING;       // 默认的选择模式
    private static final String SELECT_MODE = "select_mode";         // key

    // view
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvConfirm;

    private BreadCrumbsView mBreadCrumbsView;
    private LinkedList<Fragment> mFragmentList = new LinkedList<>();

    // 单选文件 - activity
    public static void selectSingleFile(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, FilesManager.class);
        intent.putExtra(SELECT_MODE, SELECT_MODE_SING);
        activity.startActivityForResult(intent, requestCode);
    }

    // 单选文件 - Fragment
    public static void selectSingleFile(Fragment fragment, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), FilesManager.class);
        intent.putExtra(SELECT_MODE, SELECT_MODE_SING);
        fragment.startActivityForResult(intent, requestCode);
    }

    // 多选文件 - Activity
    public static void selectMultipleFile(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, FilesManager.class);
        intent.putExtra(SELECT_MODE, SELECT_MODE_MULTIPLE);
        activity.startActivityForResult(intent, requestCode);
    }

    // 多选文件 - Fragment
    public static void selectMultipleFile(Fragment fragment, int requestCode) {
        Intent intent = new Intent(fragment.getActivity(), FilesManager.class);
        intent.putExtra(SELECT_MODE, SELECT_MODE_MULTIPLE);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_files_manager);

        SELECT_MODE_DEFAULT = getIntent().getIntExtra(SELECT_MODE, SELECT_MODE_SING);

        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvConfirm = (TextView) findViewById(R.id.tvConfirm);
        mBreadCrumbsView = findViewById(R.id.mBreadCrumbsView);

        tvTitle.setText("选择文件");

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.putExtra("fileName", fileName);
                intent.putExtra("filePath", filePath);
                setResult(SELECT_FILE_RESULT_CODE, intent);
                finish();
            }
        });

        mBreadCrumbsView.setOnTabListener(new BreadCrumbsView.OnTabListener() {
            @Override
            public void onAdded(BreadCrumbsView.Tab tab) {
                Log.d("BreadCrumbsView", "onAdded：" + tab.getIndex());
                addFragment(tab);
            }

            @Override
            public void onActivated(BreadCrumbsView.Tab tab) {
                Log.d("BreadCrumbsView", "onActivated：" + tab.getIndex());
            }

            @Override
            public void onRemoved(BreadCrumbsView.Tab tab) {
                Log.d("BreadCrumbsView", "onRemoved：" + tab.getIndex());
                removeLastFragment();
            }
        });

        // 默认添加一个    首页
        StringBuilder sb = new StringBuilder("首页");
        HashMap<String, String> map = new HashMap<>();// map存放在tab上，创建Fragment时通过tab.getValue获取
        map.put("path", "home");
        mBreadCrumbsView.addTab(sb.toString(), map);
    }

    // 添加一个fragment
    private void addFragment(BreadCrumbsView.Tab tab) {
        Map<String, String> value = tab.getValue();
        String path = value.get("path");
        if (path.equals("home")) {
            Fragment fragment = HomeFragment.open();
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.mFrameLayout, fragment, String.valueOf(tab.getIndex()))
                    .show(fragment)
                    .addToBackStack(null)
                    .commit();
            mFragmentList.add(fragment);
        } else {
            Fragment fragment = FileListFragment.open(path);
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.mFrameLayout, fragment, String.valueOf(tab.getIndex()))
                    .show(fragment)
                    .addToBackStack(null)
                    .commit();
            mFragmentList.add(fragment);
        }

    }

    // 移除最后一个Fragment，显示倒数第二个Fragment
    private void removeLastFragment() {
        if (mFragmentList != null && mFragmentList.size() > 1) {
            getSupportFragmentManager().popBackStackImmediate();
            mFragmentList.removeLast();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .show(mFragmentList.getLast())
                    .commit();
            fragmentManager.executePendingTransactions();
        }
    }

    /**
     * EventBus 数据和事件分发
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DataEvent event) {
        switch (event.type) {
            case TO_NEXT_FOLDER:
                FileBean bean = (FileBean) event.data;
                String title = bean.getName();
                String path = bean.getPath();

                HashMap<String, String> map = new HashMap<>();// map存放在tab上，创建Fragment时通过tab.getValue获取
                map.put("path", path);

                mBreadCrumbsView.addTab(title, map);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Override
    public void onBackPressed() {
        if (mFragmentList != null && mFragmentList.size() > 1) {
            mBreadCrumbsView.selectAt(mFragmentList.size() - 1 - 1);
        } else {
//            AlertDialog dialog = new AlertDialog.Builder(this)
//                    .setTitle("提示")
//                    .setMessage("确认退出么?")
//                    .setCancelable(true)
//                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    }).create();
//            dialog.show();
            finish();
        }
    }
}